package com.liuguang.picture.service.impl;

import com.liuguang.api.picture.PictureService;
import com.liuguang.common.enums.CommonResultEnum;
import com.liuguang.common.exceptions.GlobalException;
import com.liuguang.common.pojo.CommonResult;
import com.liuguang.picture.utils.QiNiuUtil;
import com.qiniu.util.Auth;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @ClassName: PictureServiceImpl
 * @Description：
 * @Author: wanghr
 * Date: 11:23 AM 2020/10/22
 * Version: 1.0
 */
@DubboService
@Service
public class PictureServiceImpl implements PictureService {
    private static final Logger logger = LoggerFactory.getLogger(PictureServiceImpl.class);

    @Value("${qiniuyun.AccessKey}")
    private String accessKey;

    @Value("${qiniuyun.SecretKey}")
    private String secretKey;

    @Value("${qiniuyun.bucket}")
    private String bucket;

    @Override
    public CommonResult getUpToken() {
//        logger.info("获取的accessKey：{}", accessKey);
//        logger.info("获取的secretKey：{}", secretKey);
//        logger.info("获取的bucket：{}", bucket);

        String upToken = QiNiuUtil.getUpToken(accessKey, secretKey, bucket);
        return CommonResult.success(CommonResultEnum.SUCCESS.getMsg(), upToken);
    }

    @Override
    public CommonResult upLoadToQiNiu(HttpServletRequest request) {
        Collection<Part> parts = null;
        try {
            parts = request.getParts();
            if (parts.size() == 0) {
                return CommonResult.success("请求中未获取到文件信息");
            }
            ArrayList<String> urlList = new ArrayList<>();
            parts.stream().forEach(part -> {
                InputStream inputStream = null;
                try {
                    inputStream = part.getInputStream();
                } catch (IOException e) {
                    logger.info("part获取输入流失败");
                    e.printStackTrace();
                }
                String fileName = "";
//                String upToken = QiNiuUtil.getUpToken(accessKey, secretKey, bucket);
                String upToken = "HKZX2myyiME_Ewt1yaf8jXCpsYY-z2IjEknQHywP:J3OIiyAUrokkTooQ4cqaqMa5DCk=:eyJzY29wZSI6Im15c3lzdGVybSIsImRlYWRsaW5lIjoxNjAzMzY1ODU3fQ==";
                String url = QiNiuUtil.upLoadPictureToQiNiu(fileName,upToken, inputStream);
                logger.info("路径:{}", url);
                urlList.add(url);
            });
            return CommonResult.success("文件上传成功",urlList);
        } catch (Exception e) {
            logger.info("文件上传失败");
            throw new GlobalException("文件上传失败");
        }
    }
}
